package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/password")
public class PasswordController {

    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("/update")
    public String update(){
        return "password/updatePwd";
    }

    @RequestMapping("/reset")
    public String reset(Long id,Model model){
        Employee employee = employeeService.get(id);
        model.addAttribute("employee",employee);
        return "password/resetPwd";
    }

    @RequestMapping("/resetPwd")
    public String resetPwd(Long uid,String newPassword){
        employeeService.updatePwd(uid,newPassword);
        return "redirect:/employee/list.do";
    }

    @RequestMapping("/updatePwd")
    @ResponseBody
    public JsonResult updatePwd(String oldPassword,String newPassword,HttpSession session){


        try {
            // 1. 从 session 获取当前用户名
            Employee employee = (Employee) session.getAttribute("USER_IN_SESSION");

            session.getAttribute("USER_IN_SESSION");

            System.out.println(employee);

            Long id = employee.getId();
            String name = employee.getName();

            // 2. 使用页面传递过来的原密码进行验证
            Employee emp = employeeService.login(employee.getName(), oldPassword);


            // 3. 如果验证通过,修改新密码并返回
            employeeService.updatePwd(emp.getId(), newPassword);
            try {
                // 清除 session 信息
                session.setAttribute("USER_IN_SESSION",null);
                return new JsonResult();
            }catch (Exception ee){
                ee.printStackTrace();
                return new JsonResult(false,ee.getMessage());
            }

        }catch (Exception e){
            e.printStackTrace();
            // 4. 如果验证不通过,提示错误信息
            return new JsonResult(false,e.getMessage());
        }


    }
}
